<template>
    <form @submit.prevent="submitForm">
        <label for="username">用户名</label>
        <input type="text" id="username" v-model="formData.username">
        <span v-if="usernameError">{{ usernameError }}</span>
        <label for="email">邮箱</label>
        <input type="email" id="email" v-model="formData.email"> 
        <span v-if="emailError">{{ emailError }}</span>

        <input type="submit" value="提交">
    </form>
</template>
<script setup>
import { ref } from 'vue'
    const formData = ref({
        username: '',
        email: ''
    })
    const usernameError = ref('')
    const emailError = ref('')
    const submitForm=()=>{
        usernameError.value='';
        emailError.value='';
        if(formData.value.username.trim()===''){
            usernameError.value='用户名不能为空'
        }
        const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        if(!emailRegex.test(formData.value.email)){
            emailError.value='邮箱格式不正确'
        }
        if(!usernameError.value && !emailError.value){
            console.log('表单验证通过提交成功')
        }
    }
</script>